<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElMessage } from 'element-plus'
import { Table } from '@/components/Table'
import { storeIndex, storeAdd, storeEdit, storeDel, placestartSelect } from '@/api/common'
import { useTable } from '@/hooks/web/useTable'
import { storageType } from '@/api/common/types'
import { ref, unref, reactive } from 'vue'
import Write from './components/addWrite.vue'
import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useCache } from '@/hooks/web/useCache'
const appStore = useAppStoreWithOut()
const { wsCache } = useCache()
//用户权限数组
const userRlues = wsCache.get(appStore.getUserInfo).rlues
const userId = wsCache.get(appStore.getUserInfo).id

const checkRlues = (rlues) => {
  //检查权限
  if (userRlues.includes(rlues)) {
    return true
  } else {
    ElMessage.error('当前用户无权限操作，请联系管理员')
    return false
  }
}

const { register, tableObject, methods } = useTable<storageType>({
  getListApi: storeIndex,
  delListApi: storeDel,
  response: {
    list: 'data',
    total: 'total'
  },
  defaultParams: {
    title: ''
  },
  find: ''
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()
const AddressList = ref([])
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'name',
    label: t('warehouseManagement.warehouseName'),
    search: {
      show: true
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'type',
    label: '仓库类型',
    search: {
      show: true,
      component: 'Select',
      componentProps: {
        filterable: true,
        options: [
          { label: '国内仓库', type: '1' },
          { label: '分货市场', type: '2' }
        ]
      }
    },
    form: {
      colProps: {
        span: 24
      },
      component: 'Select',
      componentProps: {
        filterable: true,
        options: [
          { label: '国内仓库', value: '1' },
          { label: '分货市场', value: '2' }
        ]
      }
    },
    table: {
      show: false
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'type_text',
    label: '仓库类型',
    form: {
      show: false
    },
    table: true,
    detail: {
      span: 24
    }
  },
  {
    field: 'placestart_id',
    label: t('router.origin'),
    search: {
      show: true,
      component: 'Select',
      api: async () => {
        const res: any = await placestartSelect({})
        let list: any = []

        res.data.list.forEach((item) => {
          list.push({
            label: item.name,
            value: item.id
          })
        })
        AddressList.value = list
        localStorage.setItem('placestartSelectData', JSON.stringify(list))
        return list
      },
      componentProps: {
        filterable: true,
        options: []
      }
    },
    form: {
      colProps: {
        span: 24
      },
      component: 'Select',
      api: async () => {
        const res: any = await placestartSelect()
        let list: any = []
        res.data.list.forEach((item) => {
          list.push({
            label: item.name,
            value: item.id
          })
        })
        localStorage.setItem('placestartSelectData', JSON.stringify(list))
        return list
      },
      componentProps: {
        filterable: true,
        options: []
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const AddAction = (rules) => {
  if (!checkRlues(rules)) return false
  dialogTitle.value = t('exampleDemo.add')
  tableObject.currentRow = null
  dialogVisible.value = true
  actionType.value = ''
}

const delLoading = ref(false)

const delData = async (row: storageType | null, multiple: boolean, rules: string) => {
  if (!checkRlues(rules)) return false
  tableObject.currentRow = row
  const { delList, getSelections } = methods
  const selections = await getSelections()
  delLoading.value = true
  await delList(
    multiple ? selections.map((v) => v.id) : [tableObject.currentRow?.id as string],
    multiple
  ).finally(() => {
    delLoading.value = false
  })
}

const actionType = ref('')

const action = (row: storageType, type: string, rules: string) => {
  if (!checkRlues(rules)) return false
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  tableObject.currentRow = row
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const loading = ref(false)

const addSave = async () => {
  const write = unref(writeRef)
  await write?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data = (await write?.getFormData()) as storageType
      const res = await storeAdd(data)
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
      if (res) {
        dialogVisible.value = false
        tableObject.currentPage = 1
        getList()
      }
    }
  })
}
const save = async () => {
  const write = unref(writeRef)
  await write?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data = (await write?.getFormData()) as storageType
      const res = await storeEdit(data, data.id)
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
      if (res) {
        dialogVisible.value = false
        tableObject.currentPage = 1
        getList()
      }
    }
  })
}
const selAddress = (id) => {
  let list = AddressList.value
  let data: any = list.find((item: any) => {
    return item.value == id
  })
  return data.label
}
</script>

<template>
  <ContentWrap>
    <Search
      :model="{}"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <div class="mb-10px">
      <ElButton type="primary" @click="AddAction('28-1')">{{ t('exampleDemo.add') }}</ElButton>
      <ElButton :loading="delLoading" type="danger" @click="delData(null, true, '28-3')">
        {{ t('exampleDemo.del') }}
      </ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.limit"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      @register="register"
    >
      <template #placestart_id="{ row }"> {{ selAddress(row.placestart_id) }} </template>
      <template #action="{ row }">
        <ElButton type="primary" @click="action(row, 'edit', '28-2')">
          {{ t('exampleDemo.edit') }}
        </ElButton>
        <ElButton type="success" @click="action(row, 'detail', '28-4')">
          {{ t('router.watch') }}
        </ElButton>
        <ElButton type="danger" @click="delData(row, false, '28-3')">
          {{ t('exampleDemo.del') }}
        </ElButton>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />

    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <template #footer>
      <ElButton
        v-if="actionType !== 'detail' && actionType !== 'edit'"
        type="primary"
        :loading="loading"
        @click="addSave"
      >
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton v-if="actionType == 'edit'" type="primary" :loading="loading" @click="save">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
